//
//  TRMyOrderViewController.m
//  WeiMiLan
//
//  Created by anan on 15/8/7.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TRMyOrderViewController.h"
#import "TREmptyViewController.h"
#import "TRMessageVeiw.h"
#import "TRCommentMineController.h"
#import "TRMsgViewController.h"


@interface TRMyOrderViewController ()<TRMessageVeiwDelegaet>
{
    MJRefreshHeaderView *refreshHeaderView;
    MJRefreshFooterView *refreshFooterView;
}

@property (weak, nonatomic) TRMessageVeiw *headerView;

@end

@implementation TRMyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"TRMyOrderViewController");
    self.contents = [[NSMutableArray alloc] init];
    [self initNavigation];
    
    UINib *nib1 = [UINib nibWithNibName:@"TROrderTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"TROrderTableViewCellID"];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    TRMessageVeiw *headerView = [TRMessageVeiw messageVeiw];
    headerView.size = CGSizeMake(self.view.frame.size.width, 118);
    self.tableView.tableHeaderView = headerView;
    headerView.delegate = self;
    self.headerView = headerView;
    
    [self addHeader];
    [self addFooter];
}

- (void)messageVeiwDidClickedBtnIndex:(TRMessageVeiw *)messageView btnClickIndex:(NSInteger)btnClickIndex {
    
    switch (btnClickIndex) {
        case 1:
        {
            TRMsgViewController *vc = [[TRMsgViewController alloc]init];
            // vc.view.backgroundColor = [UIColor greenColor];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 2:
        {
            TRCommentMineController *vc = [[TRCommentMineController alloc]init];
           // vc.view.backgroundColor = [UIColor greenColor];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
       
            break;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"kRefreshComment" object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [refreshHeaderView beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refresh {
    [refreshHeaderView beginRefreshing];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *nickname = [userInfo ql_stringForKey:@"NAME"];
    nickname = nickname==nil?[QLPropertyUtils getStringByKey:@"account" defaultValue:nil]:nickname;
    
    self.weChatNavigationBar.titleLabel.text=@"消息";
    //[self.weChatNavigationBar.leftButton addTarget:self action:@selector(shouLeftVC) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.hidden = YES;
    self.weChatNavigationBar.leftButton.hidden = YES;
}

//-(void)shouLeftVC
//{
//    [ApplicationDelegate.ddVC showLeftController:YES];
//}

- (void)loadData:(int)num {
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyOrder?type=12002&userId=%@&pageNum=%d";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,num];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
  //  NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        
        if (num<=1) {
            //第一页
            if ([resultDic[@"USER_INFO_RSP"][@"ORDER_INFO"] isKindOfClass:[NSDictionary class]]) {
                [self.contents addObject:resultDic[@"USER_INFO_RSP"][@"ORDER_INFO"]];
            }else{
                self.contents = [NSMutableArray arrayWithArray:resultDic[@"USER_INFO_RSP"][@"ORDER_INFO"]];
            }
        }else{
            [self.contents addObjectsFromArray:resultDic[@"USER_INFO_RSP"][@"ORDER_INFO"]];
        }

        
        NSDictionary *pageInfo = resultDic[@"PAGE_INFO"];
        self.nextPage = [pageInfo ql_intForKey:@"NEXT"];
        self.currentPage = [pageInfo ql_intForKey:@"NUMBER"];
        if (self.nextPage>self.currentPage) {
            refreshFooterView.isend = NO;
        }else{
            refreshFooterView.isend = YES;
        }
        [self endRefresh];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   // long count = self.contents==nil?5:self.contents.count;
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TROrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TROrderTableViewCellID"];
    if (cell == nil) {
        cell = [[TROrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TROrderTableViewCell"];
    }
//    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
//    cell.info = info;
    
    cell.imageViewAvator.image = [UIImage resizebleImage:[UIImage imageNamed:@"avator"]];
    cell.labelId.text = @"再海两方";
  
    [cell setNeedsDisplay];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    TROrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRBuyCarTableViewCell"];
//    if (cell == nil) {
//        cell = [[TROrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRBuyCarTableViewCell"];
//    }
//    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
//    cell.info = info;
    return 59;//[cell getHeight];
   
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
//    NSMutableDictionary *dic = [self.contents objectAtIndex:indexPath.row];
//    
//    TROrderDetailViewController *vc = [[TROrderDetailViewController alloc] init];
//    vc.orderId = [dic ql_stringForKey:@"ID"];
    TREmptyViewController *vc = [[TREmptyViewController alloc]init];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData:0];
    };
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    refreshFooterView = footer;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData:self.nextPage];
    };
}

- (void)endRefresh
{
    // 刷新表格
    [self.tableView reloadData];
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
}

@end
